package com.ccp.dev.workflow.controller;

import com.ccp.dev.core.basic.annotion.Action;
import com.ccp.dev.core.basic.consts.UrlConstants;
import com.ccp.dev.core.basic.internationalization.SysBaseController;
import com.ccp.dev.core.basic.model.SysAuditModelType;
import com.ccp.dev.core.basic.response.ResultData;
import com.ccp.dev.core.basic.util.UUIDUtils;
import com.ccp.dev.core.basic.web.query.QueryFilter;
import com.ccp.dev.core.util.RequestUtil;
import com.ccp.dev.core.util.StringUtil;
import com.ccp.dev.workflow.model.ActDefModel;
import com.ccp.dev.workflow.model.BpmNodeMessage;
import com.ccp.dev.workflow.model.BpmUserCondition;
import com.ccp.dev.workflow.model.SysTemplate;
import com.ccp.dev.workflow.service.ActDefModelService;
import com.ccp.dev.workflow.service.BpmNodeMessageService;
import com.ccp.dev.workflow.service.BpmUserConditionService;
import com.ccp.dev.workflow.service.SysTemplateService;
import net.sf.json.JSONArray;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.ArrayList;
import java.util.List;

/**
 * ClassDescribe:
 * 流程节点信息控制器
 * @author :wangcheng
 * Date: 2019-07-17
 */
@Controller
@RequestMapping(UrlConstants.PROJECT_ROOT + UrlConstants.PROJECT_MODULE_WORKFLOW + "/bpmNodeMessage")
@Action(ownermodel = SysAuditModelType.PROCESS_MANAGEMENT)
public class BpmNodeMessageController extends SysBaseController {
    @Resource
    private BpmNodeMessageService bpmNodeMessageService;
    @Resource
    private ActDefModelService actDefModelService;
    @Resource
    private BpmUserConditionService bpmUserConditionService;
    @Resource
    private SysTemplateService sysTemplateService;

    /**
     * 跳转节点消息编辑页面
     * @param request http请求
     * @param model mvc模型对象
     * @return 消息编辑页面
     */
    @RequestMapping(UrlConstants.VIEW_DISPATCH_PREFIX + "/edit")
    @Action(description = "跳转节点消息编辑页面", detail = "跳转节点消息编辑页面")
    public String viewEdit(HttpServletRequest request, Model model) {
        List<SysTemplate> sysTemplateList = sysTemplateService.queryList(new QueryFilter(request));
        String procDefId = RequestUtil.getString(request, "procDefId");
        String nodeId = RequestUtil.getString(request, "nodeId");

        List<BpmUserCondition> bpmUserConditions = bpmUserConditionService.queryByProcDefIdAndNodeId(procDefId, nodeId);

        List<BpmUserCondition> receiverMailConds = new ArrayList<>();
        List<BpmUserCondition> copyToMailConds = new ArrayList<>();
        List<BpmUserCondition> bccMailConds = new ArrayList<>();
        List<BpmUserCondition> receiverMobileConds = new ArrayList<>();
        List<BpmUserCondition> receiverInnerCondes = new ArrayList<>();

        // 对用户选择条件按照不同的条件类型进行分类
        for (BpmUserCondition condition : bpmUserConditions) {
            if (condition.getConditionType() == null) {
                continue;
            }
            switch (condition.getConditionType()) {
                case BpmUserCondition.CONDITION_TYPE_MSG_MAIL_RECEIVER:
                    receiverMailConds.add(condition);
                    break;
                case BpmUserCondition.CONDITION_TYPE_MSG_MAIL_COPYTO:
                    copyToMailConds.add(condition);
                    break;
                case BpmUserCondition.CONDITION_TYPE_MSG_MAIL_BCC:
                    bccMailConds.add(condition);
                    break;
                case BpmUserCondition.CONDITION_TYPE_MSG_MOBILE_RECEIVER:
                    receiverMobileConds.add(condition);
                    break;
                case BpmUserCondition.CONDITION_TYPE_MSG_INNER_RECEIVER:
                    receiverInnerCondes.add(condition);
                    break;
                default:
                    break;

            }
        }

        List<BpmNodeMessage> bpmNodeMessages = bpmNodeMessageService.queryByProcDefIdAndNodeId(procDefId, nodeId);
        ActDefModel actDefModel = actDefModelService.getByProcDefId(procDefId);
        BpmNodeMessage mailMessage = null;
        BpmNodeMessage innerMessage = null;
        BpmNodeMessage smsMessage = null;

        // 判断发送消息类型
        for (BpmNodeMessage message : bpmNodeMessages) {
            Short messageType = message.getMessageType();
            if (messageType == null) {
                messageType = -1;
            }

            switch (messageType) {
                case BpmNodeMessage.MESSAGE_TYPE_MAIL:
                    mailMessage = message;
                    break;
                case BpmNodeMessage.MESSAGE_TYPE_INNER:
                    innerMessage = message;
                    break;
                case BpmNodeMessage.MESSAGE_TYPE_SMS:
                    smsMessage = message;
                    break;
                default:
                    break;
            }

        }

        model.addAttribute("modelId", actDefModel.getId())
            .addAttribute("procDefId", procDefId)
            .addAttribute("nodeId", nodeId)

            .addAttribute("mailMessage",mailMessage)
            .addAttribute("innerMessage", innerMessage)
            .addAttribute("smsMessage",smsMessage)

            .addAttribute("receiverMailConds", receiverMailConds)
            .addAttribute("copyToMailConds", copyToMailConds)
            .addAttribute("bccMailConds", bccMailConds)
            .addAttribute("receiverInnerCondes",receiverInnerCondes)
            .addAttribute("receiverMobileConds",receiverMobileConds)

            .addAttribute("receiverMailCondJsons", JSONArray.fromObject(receiverMailConds).toString())
            .addAttribute("bccMailCondJsons", JSONArray.fromObject(bccMailConds).toString())
            .addAttribute("copyToMailCondJsons", JSONArray.fromObject(copyToMailConds).toString())
            .addAttribute("receiverInnerCondJsons", JSONArray.fromObject(receiverInnerCondes).toString())
            .addAttribute("receiverMobileCondJsons", JSONArray.fromObject(receiverMobileConds).toString())

            .addAttribute("sysTemplateList", sysTemplateList);
        return getAutoView();
    }

    /**
     * 节点信息数据保存
     * @param request http请求
     * @return 操作封装结果集
     */
    @RequestMapping("/save")
    @Action(description = "节点信息数据保存", detail = "节点信息数据保存")
    @ResponseBody
    public ResultData save(HttpServletRequest request) {
        String procDefId = RequestUtil.getString(request, "procDefId");
        String nodeId = RequestUtil.getString(request, "nodeId");
        String subjectMail = RequestUtil.getString(request, "subject_mail");
        String templateMail = RequestUtil.getString(request, "template_mail");

        String subjectInner = RequestUtil.getString(request, "subject_inner");
        String templateInner = RequestUtil.getString(request, "template_inner");

        String templateMobile = RequestUtil.getString(request, "template_mobile");

        Short sendMail = RequestUtil.getShort(request, "sendMail");
        Short sendInner = RequestUtil.getShort(request, "sendInner");
        Short sendMobile = RequestUtil.getShort(request, "sendMobile");
        String mailMessageId = RequestUtil.getString(request, "mailMessageId");
        String innerMessageId = RequestUtil.getString(request, "innerMessageId");
        String smsMessageId = RequestUtil.getString(request, "smsMessageId");

        List<BpmNodeMessage> messages= new ArrayList<>(3);

        // 封装邮件信息
        BpmNodeMessage mailMessage=new BpmNodeMessage();
        mailMessage.setId(mailMessageId);
        mailMessage.setProcDefId(procDefId);
        mailMessage.setNodeId(nodeId);
        mailMessage.setSubject(subjectMail);
        mailMessage.setMessageType(BpmNodeMessage.MESSAGE_TYPE_MAIL);
        mailMessage.setTemplate(templateMail);
        mailMessage.setIsSend(sendMail);

        // 封装内部消息
        BpmNodeMessage innerMessage=new BpmNodeMessage();
        innerMessage.setId(innerMessageId);
        innerMessage.setProcDefId(procDefId);
        innerMessage.setNodeId(nodeId);
        innerMessage.setSubject(subjectInner);
        innerMessage.setMessageType(BpmNodeMessage.MESSAGE_TYPE_INNER);
        innerMessage.setTemplate(templateInner);
        innerMessage.setIsSend(sendInner);

        // 封装短信消息
        BpmNodeMessage smsMessage=new BpmNodeMessage();
        smsMessage.setId(smsMessageId);
        smsMessage.setProcDefId(procDefId);
        smsMessage.setNodeId(nodeId);
        smsMessage.setMessageType(BpmNodeMessage.MESSAGE_TYPE_SMS);
        smsMessage.setTemplate(templateMobile);
        smsMessage.setIsSend(sendMobile);

        messages.add(mailMessage);
        messages.add(innerMessage);
        messages.add(smsMessage);

        for (BpmNodeMessage message : messages) {
            if (StringUtil.isEmpty(message.getId())) {
                message.setId(UUIDUtils.getUUIDFor32());
                bpmNodeMessageService.add(message);
            }else {
                bpmNodeMessageService.update(message);
            }
        }

        return getResultDataSuccess("save.success");

    }

    /**
     * 消息节点，消息接受人员，人员规则设置
     *
     * @param request http请求
     * @return 跳转路径
     */
    @RequestMapping("/receiverSetting")
    @Action(description = "消息节点，消息接受人员，人员规则设置", detail = "消息节点，消息接受人员，人员规则设置")
    public String receiverSetting(HttpServletRequest request, Model model) {
        String procDefId = RequestUtil.getString(request, "procDefId");
        String nodeId = RequestUtil.getString(request, "nodeId");
        int type = RequestUtil.getInt(request, "type");

        ActDefModel actDefModel = actDefModelService.getByProcDefId(procDefId);

        List<BpmUserCondition> receiverSetting = getBpmUserConditions(procDefId, nodeId, type);

        model.addAttribute("receiverSetting", receiverSetting);
        model.addAttribute("actDefModel", actDefModel);
        model.addAttribute("nodeId", nodeId);
        model.addAttribute("conditionType", type);
        return "workflow/bpmNodeMessage/receiverSetting";
    }

    /**
     * 根据参数获取节点用户条件
     * @param procDefId 流程定义id
     * @param nodeId 节点id
     * @param type 消息类型
     * @return 获取人员选择条件列表
     */
    private List<BpmUserCondition> getBpmUserConditions(String procDefId, String nodeId, int type) {
        List<BpmUserCondition> userConditions = null;
        switch (type) {
            case BpmUserCondition.CONDITION_TYPE_MSG_MAIL_RECEIVER:
                break;
            case BpmUserCondition.CONDITION_TYPE_MSG_MAIL_COPYTO:
                break;
            case BpmUserCondition.CONDITION_TYPE_MSG_MAIL_BCC:
                break;
            case BpmUserCondition.CONDITION_TYPE_MSG_INNER_RECEIVER:
                userConditions = bpmUserConditionService.getReceiverInnerConditions(procDefId, nodeId);
                break;
            case BpmUserCondition.CONDITION_TYPE_MSG_MOBILE_RECEIVER:
                break;
            case BpmUserCondition.CONDITION_TYPE_TRIGGER_NEWFLOW_STARTUSER:
                userConditions = bpmUserConditionService.getTriggerNewFlowStartUserConditions(procDefId, nodeId);
                break;
            default:
                userConditions = new ArrayList<>();
                break;
        }
        return userConditions;
    }

    /**
     * 获取节点用户设置条件信息
     * @param request http请求
     * @return 用户选择条件信息列表
     */
    @RequestMapping("/getReceiverUserCondition")
    @ResponseBody
    @Action(description = "获取节点用户设置条件信息", detail = "获取节点用户设置条件信息")
    public ResultData getReceiverUserCondition(HttpServletRequest request) {
        try {
            String procDefId = RequestUtil.getString(request, "procDefId");
            String nodeId = RequestUtil.getString(request, "nodeId");
            int type = RequestUtil.getInt(request, "receiverType");
            List<BpmUserCondition> userConditions = getBpmUserConditions(procDefId, nodeId, type);
            return getResultDataSuccess("operate.success", userConditions);
        }catch (Exception e) {
            return getResultDataError("operate.failure");
        }
    }
}
